//
//  EditGoodsController.m
//  YiBaoStore
//
//  Created by 毛云河 on 2018/12/2.
//  Copyright © 2018 小河. All rights reserved.
//

#import "EditGoodsController.h"
#import "PicturePicker.h"


#define PictureSize (SCREENWIDTH-80-40)/5
#define interval 10

@interface EditGoodsController ()<UITextFieldDelegate,TZImagePickerControllerDelegate>

@property (nonatomic, strong) UIScrollView *myScrollView;

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIView *downView;

@property (nonatomic, strong) UITextField *codeTF;

@property (nonatomic, strong) UITextField *titleTF;
@property (nonatomic, strong) UILabel *titleFuLabel;
@property (nonatomic, strong) UIView *titleLine;

@property (nonatomic, strong) UITextField *costTF;
@property (nonatomic, strong) UILabel *costFuLabel;
@property (nonatomic, strong) UIView *costLineView;

@property (nonatomic, strong) UITextField *saleTF;
@property (nonatomic, strong) UITextField *storesTF;


@property (nonatomic, strong) UIImageView *addImg;
@property (nonatomic, strong) PicturePicker *picturePicker;
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, copy) NSString *showImageUrl;

@end

@implementation EditGoodsController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNav];
    [self createScrollView];
    [self createTopView];
    [self createDownView];
    
    [self uploadData];
}

- (void)uploadData
{
    self.codeTF.text = [NSString stringWithFormat:@"%@",self.model.barcode];//商品条码
    self.titleTF.text = [NSString stringWithFormat:@"%@",self.model.title];//商品标题
    CGFloat shopCostPrice = [(NSString *)self.model.shopCostPrice floatValue];
    self.costTF.text = [NSString stringWithFormat:@"%0.2f",shopCostPrice];//商品成本价
    CGFloat price = [(NSString *)self.model.price floatValue];
    self.saleTF.text = [NSString stringWithFormat:@"%0.2f",price];//商品销售价
    
    if (IsEmptyStr(self.model.stockAmount))
    {
        self.storesTF.text = [NSString stringWithFormat:@"%@",@"9999"];//商品库存
    }
    else {
        self.storesTF.text = [NSString stringWithFormat:@"%@",self.model.stockAmount];//商品库存
    }
    
    if (self.index == 1)
    {//上架商品
        self.codeTF.userInteractionEnabled = NO;
        self.titleTF.userInteractionEnabled = NO;
        self.titleFuLabel.hidden = YES;
        self.titleLine.hidden = YES;
        if ([self.model.type isEqualToString:@"2"])
        {
            self.costTF.userInteractionEnabled = NO;
            self.costLineView.hidden = YES;
            self.costFuLabel.hidden = YES;
        }
    }
    else {//审核商品和仓库商品
        if ([self.model.type isEqualToString:@"2"])
        {
            self.costTF.userInteractionEnabled = NO;
            self.costLineView.hidden = YES;
            self.costFuLabel.hidden = YES;
        }
    }
    
    if ([self.model.type isEqualToString:@"1"])
    {//自采商品
        self.titleTF.userInteractionEnabled = NO;
        self.titleFuLabel.hidden = YES;
        self.titleLine.hidden = YES;
        
        self.costTF.userInteractionEnabled = NO;
        self.costLineView.hidden = YES;
        self.costFuLabel.hidden = YES;
    }
    
    if (self.index == 4)
    {
        self.imageArray = [NSMutableArray arrayWithObject:self.model.showImage];
    }
    else {
        self.imageArray = [NSMutableArray arrayWithArray:self.model.imageUrlList];
    }
    
    [self reloadTopImage];
}

#pragma mark - 设置导航
- (void)setNav
{
    //显示右导航
    self.titLabel.text = @"编辑商品";
}

- (void)createScrollView
{
    self.myScrollView = [[UIScrollView alloc] init];
    [self.view addSubview:self.myScrollView];
    self.myScrollView.scrollEnabled = YES;   // 默认为YES
    if (@available(iOS 11.0, *))
    {
        self.myScrollView.frame = CGRectMake(0, self.bgNavView.bottom, SCREENWIDTH, SCREENHEIGHT-self.bgNavView.bottom-BottomHeight_xs);
    } else {
        self.myScrollView.frame = CGRectMake(0, self.bgNavView.bottom, SCREENWIDTH, SCREENHEIGHT-self.bgNavView.bottom-BottomHeight);
    }
}

- (void)createTopView
{
    UILabel *titleStr = [[UILabel alloc] init];
    [self.myScrollView addSubview:titleStr];
    titleStr.frame = CGRectMake(40, 36, 200, 12);
    titleStr.textAlignment = 0;
    titleStr.textColor = BlackTextColor;
    titleStr.font = FontWithSize(12);
    titleStr.text = @"商品首图";
    
    self.topView = [[UIView alloc] init];
    [self.myScrollView addSubview:self.topView];
    self.topView.frame = CGRectMake(0, titleStr.bottom+16, SCREENWIDTH, PictureSize);
    
    self.addImg = [[UIImageView alloc] init];
    self.addImg.backgroundColor = RGBACOLOR(248, 248, 248, 1);
    self.addImg.userInteractionEnabled = YES;
    [self.topView addSubview:self.addImg];
    _addImg.frame = CGRectMake(40, 0, PictureSize, PictureSize);
    
    UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image_btn"]];
    [self.addImg addSubview:icon];
    icon.center = self.addImg.center;
    icon.frame = CGRectMake((self.addImg.width-23)/2, (self.addImg.height-21)/2, 23, 21);
    
    UITapGestureRecognizer *addTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addTapAction:)];
    [_addImg addGestureRecognizer:addTap];

}

- (void)addTapAction:(UITapGestureRecognizer *)tap
{
    TZImagePickerController *imagePickerC = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerC.allowCrop = YES;
    imagePickerC.cropRect = CGRectMake(0, (SCREENHEIGHT-SCREENWIDTH)/2, SCREENWIDTH, SCREENWIDTH);
    [self presentViewController:imagePickerC animated:YES completion:nil];
}

#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
{
    UIImage *image = photos[0];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setValue:imageData forKey:@"file"];
    __weak __typeof(self) weakSelf = self;
    [[HttpRequest currentHttpRequest] uploadWithParams:dict andImageData:imageData block:^(NSString *SamllPhoto)
     {
         [weakSelf.imageArray addObject:SamllPhoto];
         [weakSelf reloadTopImage];
     }];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)reloadTopImage
{
    [self.topView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    if (self.imageArray.count == 0)
    {
        [self.topView addSubview:_addImg];
        _addImg.frame = CGRectMake(40, 0, PictureSize, PictureSize);
        if (self.index == 1||[self.model.type isEqualToString:@"2"])
        {
            _addImg.userInteractionEnabled = NO;
        }
        return;
    }
    
    UIImageView *lastView = nil;
    for (int i = 0; i < self.imageArray.count; i ++)
    {
        NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.imageArray[i]]];
        UIImage *image = [UIImage imageWithData:data];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        [self.topView addSubview:imageView];
        imageView.frame = CGRectMake(40+(PictureSize+interval)*(i%5), (PictureSize+interval)*(i/5), PictureSize, PictureSize);
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        [button setImage:[UIImage imageNamed:@"shopDelete"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(deletePicture:) forControlEvents:UIControlEventTouchUpInside];
        [self.topView addSubview:button];
        button.frame = CGRectMake(imageView.right-14, imageView.top-12, 25, 25);
        
        if (self.index == 1||
            self.index == 4||
            [self.model.type isEqualToString:@"2"])
        {
            button.hidden = YES;
        }
        else {
            button.hidden = NO;
        }
        
        if (i == (self.imageArray.count - 1))
        {
            lastView = imageView;
        }
    }
    
    if (lastView)
    {
        [self.topView addSubview:_addImg];
        
        if (self.index == 1||
            [self.model.type isEqualToString:@"1"])
        {//不能编辑 已经上架或者是自采商品
            _addImg.hidden = YES;
        }else {//允许编辑
            _addImg.hidden = NO;
        }
        
        if (self.imageArray.count == 5)
        {
            _addImg.frame = CGRectMake(40, lastView.bottom+interval, PictureSize, PictureSize);
            
        }
        else if (self.imageArray.count == 6)
        {
            _addImg.hidden = YES;
        }
        else {
            _addImg.frame = CGRectMake(lastView.right+interval, lastView.top, PictureSize, PictureSize);
        }
        
        UITapGestureRecognizer *addTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addTapAction:)];
        [_addImg addGestureRecognizer:addTap];
    }
    
    if (self.imageArray.count == 6)
    {
        self.topView.frame = CGRectMake(0, self.topView.top, SCREENWIDTH, lastView.bottom);
    }
    else {
        self.topView.frame = CGRectMake(0, self.topView.top, SCREENWIDTH, _addImg.bottom);
    }
    
    self.downView.frame = CGRectMake(0, self.topView.bottom+9, SCREENWIDTH, 600);
    self.myScrollView.contentSize = CGSizeMake(SCREENWIDTH, self.downView.bottom+50);
}

- (void)deletePicture:(UIButton *)button
{
    [self.imageArray removeObjectAtIndex:button.indexPath.row];
    [self reloadTopImage];
}

#pragma mark - 创建视图
- (void)createDownView
{
    self.downView = [[UIView alloc] init];
    [self.myScrollView addSubview:self.downView];
    self.downView.frame = CGRectMake(0, self.topView.bottom+9, SCREENWIDTH, 600);
    
    UILabel *imageLabel = [[UILabel alloc] init];
    [self.downView addSubview:imageLabel];
    imageLabel.frame = CGRectMake(40, 0, 200, 13);
    imageLabel.text = @"* 最多6张主图";
    imageLabel.font = FontWithSize(13);
    imageLabel.textColor = RGBACOLOR(130, 130, 130, 1);
    
    for (int i = 0; i < 5; i++)
    {
        UILabel *title = [[UILabel alloc] init];
        [self.downView addSubview:title];
        title.font = FontSemiboldSize(14);
        title.textColor = BlackTextColor;
        title.textAlignment = 0;
        title.frame = CGRectMake(40+(70)*(i%1), (imageLabel.bottom+13)+(12+68)*(i/1), 70, 14);
        
        UITextField *tf = [[UITextField alloc] init];
        [self.downView addSubview:tf];
        tf.font = FontWithSize(13);
        tf.textColor = RGBACOLOR(130, 130, 130, 1);
        tf.frame = CGRectMake(40+(SCREENWIDTH-80)*(i%1), (imageLabel.bottom+25)+(32+48)*(i/1), (SCREENWIDTH-80), 32);
        
        UIView *line = [[UIView alloc] init];
        [self.downView addSubview:line];
        line.frame = CGRectMake(40, tf.bottom+1, tf.width, 1);
        line.backgroundColor = RGBACOLOR(227, 227, 227, 1);
        
        UILabel *stakeLabel = [[UILabel alloc] init];
        [self.downView addSubview:stakeLabel];
        stakeLabel.frame = CGRectMake(40, line.bottom+5, 200, 13);
        stakeLabel.font = FontWithSize(13);
        stakeLabel.textAlignment = 0;
        stakeLabel.textColor = RGBACOLOR(130, 130, 130, 1);
        
        switch (i) {
            case 0:
            {
                title.text = @"商品条码";
                stakeLabel.text = @"* 请输入商品条码";
                stakeLabel.hidden = YES;
                line.hidden = YES;
                self.codeTF = tf;
                self.codeTF.userInteractionEnabled = NO;
            }
                break;
                
            case 1:
            {
                title.text = @"商品标题";
                stakeLabel.text = @"* 请输入商品标题";
                self.titleFuLabel = stakeLabel;
                self.titleLine = line;
                self.titleTF = tf;
            }
                break;
                
            case 2:
            {
                title.text = @"商品成本价";
                stakeLabel.text = @"* 请输入商品成本价(元)";
                tf.keyboardType = UIKeyboardTypeDecimalPad;
                tf.delegate = self;
                self.costTF = tf;
                self.costFuLabel = stakeLabel;
                self.costLineView = line;
            }
                break;
                
            case 3:
            {
                title.text = @"商品销售价";
                stakeLabel.text = @"* 请输入商品销售价(元)";
                tf.keyboardType = UIKeyboardTypeDecimalPad;
                tf.delegate = self;
                self.saleTF = tf;
            }
                break;
                
            case 4:
            {
                title.text = @"商品库存";
                if([self.model.type isEqualToString:@"1"]) {
                    stakeLabel.text = @"修改库存不能高于当前库存";
                }else {
                    stakeLabel.text = @"请输入商品库存量(默认库存9999）";
                }
                
                [stakeLabel sizeToFit];
                tf.text = @"9999";
                tf.keyboardType = UIKeyboardTypeNumberPad;
                self.storesTF = tf;
            }
                break;
                
            default:
                break;
        }
    }
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.downView addSubview:saveBtn];
    saveBtn.frame = CGRectMake(40, self.storesTF.bottom+150, SCREENWIDTH-80, 50);
    saveBtn.backgroundColor = BtnBgColor;
    saveBtn.titleLabel.font = FontWithSize(18);
    saveBtn.layer.cornerRadius = 25;
    saveBtn.layer.masksToBounds = YES;
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn setTitleColor:BlackTextColor forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.myScrollView.contentSize = CGSizeMake(SCREENWIDTH, self.downView.bottom+50);
}

#pragma mark - 编辑结束的时候
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if ([self.model.type isEqualToString:@"1"])
    {//自采商品编辑
        if (textField == self.saleTF)
        {//销售价
            float price = [self.model.price floatValue];//零售价
            float castPrice = [self.model.shopCostPrice floatValue];//成本价
            float sale = [self.saleTF.text floatValue];//用户修改的价格
            if (sale > price)
            {
                [self ShowHUDWithMessage:@"活动价不能高于零售价"];
                return NO;
            }
            
            if (sale < castPrice)
            {
                [self ShowHUDWithMessage:@"活动价不能低于成本价"];
                return NO;
            }
        }
        else if (textField == self.storesTF)
        {//库存
            NSInteger storesNumber =  [self.storesTF.text integerValue];
            NSInteger stockAmount = [self.model.stockAmount integerValue];
            if (storesNumber > stockAmount) {
                [self ShowHUDWithMessage:@"库存不能高于当前库存"];
                return NO;
            }
        }
    }
    return YES;
}


- (void)saveBtnClick
{
    if (IsEmptyStr(self.titleTF.text))
    {
        [self ShowHUDWithMessage:@"商品标题为空"];
        return;
    }
    
    if (IsEmptyStr(self.costTF.text))
    {
        [self ShowHUDWithMessage:@"商品成本价为空"];
        return;
    }
    
    if (IsEmptyStr(self.saleTF.text))
    {
        [self ShowHUDWithMessage:@"商品销售价为空"];
        return;
    }
    
    if ([self.model.type isEqualToString:@"1"])
    {//自采商品
        float price = [self.model.price floatValue];//零售价
        float castPrice = [self.model.shopCostPrice floatValue];//成本价
        float sale = [self.saleTF.text floatValue];//用户修改的价格
        if (sale > price)
        {
            [self ShowHUDWithMessage:@"活动价不能高于零售价"];
            return;
        }
        
        if (sale < castPrice)
        {
            [self ShowHUDWithMessage:@"活动价不能低于成本价"];
            return;
        }
    }
    
    float price = [self.saleTF.text floatValue];
    float castPrice = [self.costTF.text floatValue];
    if (price < castPrice)
    {
        [self ShowHUDWithMessage:@"商品销售价不能低于商品成本价"];
        return;
    }
    
    if (self.imageArray.count == 0)
    {
        [self ShowHUDWithMessage:@"商品主图不能为空"];
        return;
    }
    else {
        for (int i = 0; i < self.imageArray.count; i++)
        {
            NSString *imageUrl = self.imageArray[i];
            if (i == 0) {
                self.showImageUrl = imageUrl;
                
            }else {
                self.showImageUrl = [NSString stringWithFormat:@"%@,%@",self.showImageUrl,imageUrl];
                NSLog(@"****%@",self.showImageUrl);
            }
        }
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self.model.product_id forKey:@"itemId"];
    if (self.index == 4)
    {
        [dic setValue:self.saleTF.text forKey:@"price"];
        [dic setValue:self.storesTF.text forKey:@"amount"];
    }else
    {
        [dic setValue:self.saleTF.text forKey:@"price"];
        [dic setValue:self.showImageUrl forKey:@"showImage"];
        NSLog(@"-------%@",self.showImageUrl);
        [dic setValue:self.titleTF.text forKey:@"title"];
        [dic setValue:self.costTF.text forKey:@"shopCostPrice"];
        [dic setValue:self.storesTF.text forKey:@"amount"];
    }
    
    [HttpRequest formPostPath:EditGoods_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
    {
        if (msgModel.status == 200)
        {
            NSString *str = [NSString stringWithFormat:@"%ld",self.index];
            USER_DEFAULTS_SAVE(str, @"isReload");
            [self ShowHUDWithMessage:@"保存成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}

#pragma mark - 保证输入正确金额
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSLog(@"%@---%@",textField.text, string);
    BOOL isHaveDian = YES;
    if ([textField.text rangeOfString:@"."].location==NSNotFound) {
        isHaveDian=NO;
    }
    if ([string length]>0)
    {
        unichar single=[string characterAtIndex:0];//当前输入的字符
        
        if ((single >='0' && single<='9') || single=='.')//数据格式正确
        {
            //首字母不能为小数点
            if([textField.text length]==0){
                if(single == '.'){
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            if([textField.text length]==1 && [textField.text isEqualToString:@"0"]){
                if(single != '.'){
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            if (single=='.')
            {
                if(!isHaveDian)//text中还没有小数点
                {
                    isHaveDian=YES;
                    return YES;
                }else
                {
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            else
            {
                if (isHaveDian)//存在小数点
                {
                    //判断小数点的位数
                    NSRange ran=[textField.text rangeOfString:@"."];
                    NSInteger tt=range.location-ran.location;
                    if (tt <= 2){
                        return YES;
                    }else{
                        return NO;
                    }
                }
                else
                {
                    return YES;
                }
            }
        }else{//输入的数据格式不正确
            [textField.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
        }
    }
    else
    {
        return YES;
    }
    
}




@end
